import Vue from 'vue'
import Vuex from 'vuex'
import cart1 from './cart1/index'
import cart2 from './cart2/index'
import home from './home/index'
import my from './my/index'

import * as Util from '@/config/utils';

import fetch from '@/config/fetch'
import detail from './detail/index'


import {
  getSufreshCarts,
  getCenterCarts,
  addCartInfo,
  addCenterInfo,
  getarea
} from '../service/getData'


import {
  mutations
} from './mutations'


Vue.use(Vuex)

export const state = {
  isLoading: false,
  direction: 'forward',
  showFooter: false,
  showMask: false,
  isPosition: false,
  // 定位
  position: {
    cityCode: "",
    cityName: "",
    poiId: "",
    poiName: "",
    storeCode: "",
    storeLocation: "",
    storeName: "",
    areaId:""
  },
  area: {
    provCode: '', //省
    lesCityCode: '', //市
    distCode: '' //区
  },
  // 用户选择未保存定位
  beforePosition: {
    storeLocation: '',
    cityCode: '1000173',
    poiId: '1',
  },
  // 客户端
  client: {},
  // 苏鲜生商品购物车
  sufreshCarts: '',
  // 易购商品购物车
  centerCarts: '',
  // 苏鲜生商品购物车数量
  sufreshCartsNumber: 0,
  // 易购商品购物车数量
  centerCartsNumber: 0,
  citys: [],
  detailAddress: {},
  defaultAddress: {
    addressId: ''
  },
  userInfo: {},
  lalPosition: {
    lat:'',
    lng:''
  }
}

export const actions = {

  // 获取苏鲜生购物车
  getSufreshProducts({
    commit
  }, item) {
    let params = {
      app: 'wap',
      appVersion: '3.2.2',
      mdmCityCode: state.position.cityCode,
      storeLocation: state.position.storeLocation,
      poiId: state.position.poiId,
      areaId: state.position.areaId
    }
    getSufreshCarts(params)
      .then((products) => {
        if (products.data && products.data.cartHeadInfo) {
          commit('updateSufreshCarts', {
            products
          })
        }
      });
  }

  // 获取易购购物车
  ,
  getCenterProducts({
    commit
  }, item) { //item只针对页面进来用的,不是加入购物车用的
    if (state.area.provCode && state.area.lesCityCode && state.area.distCode) {
      fn()
    } else {
      getarea({
          storeLocation: state.position.storeLocation,
          version: '3.2.2',
          poiId: state.position.poiId,
          cityCode: state.position.cityCode
        })
        .then((json) => {
          // var provCode, lesCityCode, distCode
          if (!json.data) return;
          state.area.provCode = json.data.provCode || '100';
          state.area.lesCityCode = json.data.lesCityCode || '025';
          state.area.distCode = json.data.distCode || '02501';

          fn()
        })
    }


    function fn() {
      var data = JSON.stringify({
        "districtCode": state.area.distCode,
        "opType": "1",
        "operationStoreCode": state.position.storeLocation,
        "tempCartId": "",
        "userFlag": "0",
        "provinceCode": state.area.provCode,
        "cityCode": state.area.lesCityCode,
        "operationChannel": "50",
        "operationTerminal": "06",
        "operationEquipment": "02"
      })
      let params = {
        data: data
      }
      getCenterCarts(params)
        .then((products) => {
          if (products.data && products.data.cartHeadInfo) {
            commit('updateCenterCarts', {
              products
            })
          }
          return;
        });
    }
  }

  // 添加购物车 --添加苏鲜生购物车
  ,
  addSufreshCart({
    state,
    commit
  }, item) {
    if (!item) return
    var cmmdtyCode = item.cmmdtyCode;
    var operation = 1;
    var cmmdtyQty = 1;
    console.log(state.sufreshCarts);
    if (state.sufreshCarts && state.sufreshCarts.shopInfos) {
      var data1 = state.sufreshCarts.shopInfos;

      for (var i = 0; i < data1.length; i++) {

        for (var j = 0; j < data1[i].cmmdtyInfos.length; j++) {
          if (cmmdtyCode == data1[i].cmmdtyInfos[j].cmmdtyCode) {

            cmmdtyQty = +(data1[i].cmmdtyInfos[j].cmmdtyQty) + 1
            operation = 2;
            break;
          }
        }
      }

    }


    if (state.detail.xsqgnum > 0 && cmmdtyQty > state.detail.xsqgnum) {

      AlertBox({
        type: 'onceCancel',
        msg: '~每人限购' + state.detail.xsqgnum + '件，贪心会发胖哦，留点给别人哦',
        cancelText: '我知道了',
        alertType: 'fixed'
      })
      // state.detail.on = false;
      return;
    }
    if (cmmdtyQty > state.detail.availableQty || cmmdtyQty > 99) {
      AlertBox({
        type: 'onceCancel',
        msg: '亲，购买商品库存不足啦~先买这么多，我们会尽快补货哦',
        cancelText: '我知道了',
        alertType: 'fixed'
      })
      // state.detail.on = false;
      return;
    }


    var params = JSON.stringify({
      "app": "wap",
      "cmmdtyInfos": [{
        "itemNo": "1",
        "shopCode": item.shopCode,
        "operation": operation,
        "shopName": item.shopName,
        "sourceType": "1",
        "cmmdtyQty": cmmdtyQty,
        "tickStatus": "1",
        "cmmdtyCode": item.cmmdtyCode
      }],
      "cartHeadInfo": {
        "mdmCityCode": state.position.cityCode,
        "storeLocation": state.position.storeLocation,
        "poiId": state.position.poiId,
        "areaId": state.position.areaId
      },
      "appVersion": "3.2.2"
    })

    addCartInfo(params)
      .then((products) => {
        if (!products.data) return;
        if (products.data.cartHeadInfo && products.data.cartHeadInfo.isSuccess == 'Y') {
          commit('updateSufreshCarts', {
            products
          })
          AlertBox({
            type: 'mini',
            delay: 500,
            msg: '加入成功！'
          })
        } else {
          if (products.data.errorInfos) {
            AlertBox({
              type: 'mini',
              msg: products.data.errorInfos[0].errorMessage
            })
          }

        }

      });


  },
  // 添加购物车 --添加中心仓购物车

  addCenterCart({
    state,
    commit,
    dispatch
  }, item) {

    if (!item) return
    var cmmdtyCode = item.cmmdtyCode;
    // var operation = 1;
    var cmmdtyQty = 1;
    var num = 0;
    if (state.centerCarts && state.centerCarts.cmmdtyInfos) {
      var data1 = state.centerCarts.cmmdtyInfos;
      for (var i = 0; i < data1.length; i++) {
        // console.log(data1[i].mainCmmdtyInfo.mainCmmdtyDetailInfo.cmmdtyCode, data1[i].mainCmmdtyInfo.mainCmmdtyDetailInfo.cmmdtyQty);
        if (cmmdtyCode == data1[i].mainCmmdtyInfo.mainCmmdtyDetailInfo.cmmdtyCode) {

          num = parseInt(data1[i].mainCmmdtyInfo.mainCmmdtyDetailInfo.cmmdtyQty) + 1
          break;
        }

      }
    }


    if (state.area.provCode && state.area.lesCityCode && state.area.distCode) {

      run()

    } else {
      getarea({
          storeLocation: state.position.storeLocation,
          version: '3.2.2',
          poiId: state.position.poiId,
          cityCode: state.position.cityCode
        })
        .then((json) => {
          if (!json.data) return;

          var provCode = json.data.provCode || '100';
          var lesCityCode = json.data.lesCityCode || '025';
          var distCode = json.data.distCode || '02501';

          state.area.provCode = provCode
          state.area.lesCityCode = lesCityCode
          state.area.distCode = distCode

          run()
        })
    }

    function run() {
      var params = JSON.stringify({
        "cmmdtyInfos": [{
          "cmmdtyHeadBasicInfo": {
            "activityId": "",
            "activityType": "01",
            "itemNo": "1"
          },
          "mainCmmdtyInfo": {
            "shopCode": item.shopCode,
            "cmmdtyQty": cmmdtyQty,
            "tickStatus": "1",
            "itemNo": "2",
            "cmmdtyCode": cmmdtyCode
          }
        }],
        "cartHeadInfo": {
          "provinceCode": state.area.provCode, //省
          "cityCode": state.area.lesCityCode, //市state.position.mdmcityCode
          "operationTerminal": "06",
          "districtCode": state.area.distCode, //区
          "operationStoreCode": state.position.storeLocation,
          "operationChannel": "50",
          "operationEquipment": "02", //02手机客户端 ,06-wap
          // "tempCartId":""//03VNq3exK3KdYYueqs51Q1Us
        }
      })
      addCenterInfo(params)
        .then((products) => {
          if (!products.data) return;
          if (products.data.cartHeadInfo && products.data.cartHeadInfo.isSuccess == 'Y') {
            dispatch('getCenterProducts')
            AlertBox({
              type: 'mini',
              delay: 500,
              msg: '加入成功！'
            })
          } else {
            if (products.data.errorInfos) {
              AlertBox({
                type: 'mini',
                msg: products.data.errorInfos[0].errorMessage
              })
            }

          }

        });
    }
  }

  // 获取城市地址
  ,
  getCityList({
    state,
    commit
  }) {
    if (state.citys.length) {
      return
    }
    fetch({
      url: 'https://snxdpre.cnsuning.com/cmwsmdm-web/city/getCitys.html',
      params: {}
    }).then(res => {
      if (res.data) {
        commit('setCitysList', res.data[0].citys)
      }
    })
  }
}

export const getters = {
  // 获取购物车数量
  cartsNumber: (state) => {
    let number = state.sufreshCartsNumber + state.centerCartsNumber
    return number > 99 ? '99+' : number
  },
  position: (state) => {
    return state.position
  },
  area: (state) => {
    return state.area
  },
  beforePosition: (state) => {
    return state.beforePosition
  },
  citysArr: (state) => {
    return state.citys
  },
  detailAddress: (state) => {
    return state.detailAddress
  },
  defaultAddress: (state) => {
    return state.defaultAddress
  },
  isPosition: () => {
    return state.isPosition
  },
  sufreshCartsNumber: (state) => {
    return state.sufreshCartsNumber
  },
  userInfo: (state)=> {
    return state.userInfo
  },
  lalPosition: (state)=> {
    return state.lalPosition
  }
}


export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters,
  modules: {
    cart1,
    cart2,
    home,
    detail,
    my,
  }
})
